import netsnmp
import time
import gviz_api

community = 'public'
version = 2

description = {"Label": ("string", "Label"),
               "Value": ("number", "Value")}
#data = [{"Label": "CPU", "Value": random.randint(10,90)},
#        {"Label": "Memory", "Value": random.randint(20,50)},
#        {"Label": "Disk", "Value": random.randint(30,40)}]
#
#
#data_table = gviz_api.DataTable(description)
#data_table.LoadData(data)
#

CPU_TYPE   = '.1.3.6.1.2.1.25.3.1.3'  
CORE_USAGE = '.1.3.6.1.2.1.25.3.3.1.2.' # +ID
CORE_NAME  = '.1.3.6.1.2.1.25.3.2.1.3.' # +ID

ssCpuRawIdle   = '.1.3.6.1.4.1.2021.11.53.0'
ssCpuRawKernel = '.1.3.6.1.4.1.2021.11.55.0'
ssCpuRawSystem = '.1.3.6.1.4.1.2021.11.52.0'
ssCpuRawUser   = '.1.3.6.1.4.1.2021.11.50.0'
ssCpuRawWait   = '.1.3.6.1.4.1.2021.11.54.0'
ssCpuRawnice   = '.1.3.6.1.4.1.2021.11.51.0'

def get_cpu_usage2(host, community='public', version=2):
    try:
        s = netsnmp.Session(DestHost=host, Version=version, Community=community)
        m_idle   = netsnmp.VarList(netsnmp.Varbind(ssCpuRawIdle))
        m_kernel = netsnmp.VarList(netsnmp.Varbind(ssCpuRawKernel))
        m_system = netsnmp.VarList(netsnmp.Varbind(ssCpuRawSystem))
        m_user   = netsnmp.VarList(netsnmp.Varbind(ssCpuRawUser))
        m_wait   = netsnmp.VarList(netsnmp.Varbind(ssCpuRawWait))
        m_nice   = netsnmp.VarList(netsnmp.Varbind(ssCpuRawnice))
        

        idle1 = long(s.get(m_idle)[0])
        kernel1 = long(s.get(m_kernel)[0])
        system1 = long(s.get(m_system)[0])
        user1 = long(s.get(m_user)[0])
        wait1 = long(s.get(m_wait)[0])
        nice1 = long(s.get(m_nice)[0])

        print idle1, kernel1, system1 , user1, wait1, nice1
        time.sleep(5)
    
        idle2 = long(s.get(m_idle)[0])
        kernel2 = long(s.get(m_kernel)[0])
        system2 = long(s.get(m_system)[0])
        user2 = long(s.get(m_user)[0])
        wait2 = long(s.get(m_wait)[0])
        nice2 = long(s.get(m_nice)[0])
        
        idle = idle2 - idle1
        kernel = kernel2 - kernel1
        system = system2 - system1
        user = user2 - user1
        wait = wait2 - wait1
        nice = nice2 - nice1

        print idle2, kernel2, system2 , user2, wait2, nice2

        print idle, kernel, system , user, wait, nice
        result =  float(idle) / (kernel + idle + system + user + wait + nice) * 100
            
        a = int(100 - result)
        if a > 75:
            return 75
        else:
            return a
    except:
        return 0


def get_cpu_usage(host, community='public', version=2):

    s = netsnmp.Session(DestHost=host, Version=version, Community=community)
    vars = netsnmp.VarList(netsnmp.Varbind('.1.3.6.1.2.1.25.3.2.1.1'))

    #count resouces
    resources = s.walk(vars)
    cpu_res = {}

    temp_cpu = 0
    for res in resources:
        oid = ".1.3.6.1.2.1.25.3.2.1.2.%s" % res
        vars = netsnmp.VarList(netsnmp.Varbind(oid))
        value = s.get(vars)
        #print oid, value
        if value[0] == CPU_TYPE:
            oid = CORE_USAGE + res
            vars = netsnmp.VarList(netsnmp.Varbind(oid))
            value = s.get(vars)
            if not value[0] == None:
                print "CORE:%s, Usage:%s" % (res, value[0])
                cpu_res[res] = int(value[0])
            else:
                # This is workaround for unknown value
                if temp_cpu == 0:
                    temp_cpu = get_cpu_usage2(host, community, version)
                cpu_res[res] = temp_cpu

    return cpu_res


def index(req):
    req.add_common_vars()
    env_vars = req.subprocess_env
    getReqStr = env_vars['QUERY_STRING']
    getReqArr = getReqStr.split('&')   
    getReqDict = {}

    for item in getReqArr:   
        tempArr = item.split('=') 
        getReqDict[tempArr[0]] = tempArr[1]

    # Parse parameter for snmp connection (community, version) 
    if getReqDict.has_key('community'):
        community = getReqDict['community']
    if getReqDict.has_key('version'):
        version = int(getReqDict['version'])
 
    req.content_type = 'text/javascript'
    
    status = '200 OK'

    data = []
    cpu_res = get_cpu_usage(getReqDict['host'], community, version)
    count = 0
    for cpu in cpu_res:
        res = {"Label": "vCPU(%s)" % count, "Value": cpu_res[cpu]}
        data.append(res)
        count = count + 1

#    data = [{"Label": "CPU" , "Value": 100 },
#        {"Label": "Memory", "Value": 5},
#        {"Label": "Disk", "Value": random.randint(30,40)}]
#

    data_table = gviz_api.DataTable(description)
    data_table.LoadData(data)


    output = data_table.ToJSonResponse(columns_order=("Label", "Value"),
                                order_by="Label")


    return output

if __name__ == "__main__":
    print get_cpu_usage2('192.168.1.90')
